const router = require('koa-router')(),
  login=require('../models/firstPage.js'),
  {con}=require('mysql2/promise'),
  log=console.log;

router.prefix('/login')

router.get('/firstpage', async function (ctx, next) {
    //用于存放数据
    let arr = [];
    let essay = await login.essay();
    essay.forEach(item=>{
        arr.push({'id':item.id,'user':item.user,'title':item.title,'like':item.like});
    })
    let length = Object.keys(arr).length;
     //向arr中添加userImage属性
     arr = arr.map((item)=>{
        return {
            ...item,
            'userImage':'',
            'userName':'',
            'essayImage':'',
            'state':''
        }
    })
    //循环取出对应的user的头像图片路径
    for(let i=0;i<length;i++){
        let id = arr[i].user
        let userImage = await login.user(id);
        let userName = await login.userName(id);
        arr[i].userImage = userImage[0]?Object.values(userImage[0])[0]:null;
        arr[i].userName = userName[0]?Object.values(userName[0])[0]:null;
    }
   
    //循环取出对应的文章图片中的一张，作为封面
    for(let i=0;i<length;i++){
        let id = arr[i].id
        let essayImage = await login.essayImage(id);
        //向arr中添加图片路径
        arr[i].essayImage = essayImage[0] && Object.values(essayImage[0])[0];
    }

    //获取用户喜欢的文章
    const {userId} = ctx.query;
    let essayId = await login.likeState(userId);
    let essayLength = Object.keys(essayId).length;
    let essayArr = [];
    for(let i=0;i<essayLength;i++){
        essayArr.push(essayId[i].passageId)
    }
    length = Object.keys(arr).length;
    for(let i=0;i<length;i++){
        if(essayArr.indexOf(arr[i].id) != -1){
            arr[i].state = true;
        }else{
            arr[i].state = false;
        }
    }
    ctx.body = arr;
    
})

module.exports = router
